﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using Mozlite.Components;

namespace Mozlite.WebUI.Mvc4.Backend.Controllers
{
    /// <summary>
    /// 首页控制器。
    /// </summary>
    [AuthorizeEx(RoleLevel.Administrator)]
    public class HomeController : BaseController
    {
        /// <summary>
        /// 全局设置。
        /// </summary>
        /// <returns>全局设置。</returns>
        public ActionResult GSettings()
        {
            var settings = GlobalSettings.Current;
            if (settings.SiteDomain == null)
                settings.SiteDomain = Request.Url.DnsSafeHost;
            return View(settings);
        }

        /// <summary>
        /// 全局设置。
        /// </summary>
        /// <returns>全局设置。</returns>
        [HttpPost]
        public ActionResult GSettings(GlobalSettings settings)
        {
            if (TryValidateModel(settings))
            {
                if (settings.SiteDomain == null)
                    settings.SiteDomain = Request.Url.DnsSafeHost;
                if (settings.Save())
                    ShowLocalSuccess("GlobalSettings_SaveSuccess");
                else
                    ShowLocalError("GlobalSettings_SaveError");
            }
            return View(settings);
        }
        /// <summary>
        /// 后台设置。
        /// </summary>
        /// <returns>全局设置。</returns>
        public ActionResult BeSettings()
        {
            return View(BSettings);
        }

        /// <summary>
        /// 后台设置。
        /// </summary>
        /// <returns>全局设置。</returns>
        [HttpPost]
        public ActionResult BeSettings(BackendSettings settings)
        {
            if (TryValidateModel(settings))
            {
                if (settings.Save())
                    ShowLocalSuccess("BackendSettings_SaveSuccess");
                else
                    ShowLocalError("BackendSettings_SaveError");
            }
            return View(settings);
        }

        /// <summary>
        /// 禁用名称设置。
        /// </summary>
        /// <returns>禁用名称设置。</returns>
        public ActionResult DisallowNames()
        {
            var settings = Mozlite.Components.DisallowNames.Current;
            return View(settings);
        }

        /// <summary>
        /// 禁用名称设置。
        /// </summary>
        /// <returns>禁用名称设置。</returns>
        [HttpPost]
        public ActionResult DisallowNames(Mozlite.Components.DisallowNames settings)
        {
            if (TryValidateModel(settings))
            {
                if (settings.Save())
                    ShowLocalSuccess("DisallowNames_SaveSuccess");
                else
                    ShowLocalError("DisallowNames_SaveError");
            }
            return View(settings);
        }

        /// <summary>
        /// 禁用名称设置。
        /// </summary>
        /// <returns>禁用名称设置。</returns>
        public ActionResult EditUser()
        {
            var user = Users.GetUser(Request.Get<int>("userid")) ?? new User();
            user.Password = null;
            return View(user);
        }

        /// <summary>
        /// 禁用名称设置。
        /// </summary>
        /// <param name="model">当前模型。</param>
        /// <returns>禁用名称设置。</returns>
        [HttpPost]
        public ActionResult EditUser(User model, FormCollection form)
        {
            if(TryValidateModel(model))
            {
                if (string.IsNullOrEmpty(model.UserName))
                {
                    ShowLocalError(CreateUserStatus.UserNameNotNull);
                    return View(model);
                }
                model.UserName = model.UserName.Trim();
                if(!Regex.IsMatch(model.UserName, Consts.UserNameRegex, RegexOptions.IgnoreCase|RegexOptions.Compiled|RegexOptions.Singleline))
                {
                    ShowLocalError(CreateUserStatus.UserNameInvalid);
                    return View(model);
                }
                if (string.IsNullOrEmpty(model.DisplayName))
                {
                    model.DisplayName = model.UserName;
                }
                if (model.UserID == 0 || model.Password.HasValue())
                {
                    if (string.IsNullOrEmpty(model.Password))
                    {
                        ShowLocalError(CreateUserStatus.PasswordNotNull);
                        return View(model);
                    }
                    model.Password = model.Password.Trim();
                    if (!Regex.IsMatch(model.Password, Consts.PasswordRegex, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline))
                    {
                        ShowLocalError(CreateUserStatus.PasswordInvalid);
                        return View(model);
                    }
                    if (!model.Password.IsCaseSensitiveEqual(form["ConfirmPassword"].NullSafeTrim()))
                    {
                        ShowLocalError(CreateUserStatus.PasswordNotEqualConfirm);
                        return View(model);
                    }
                }
                if (string.IsNullOrEmpty(model.Email))
                {
                    ShowLocalError(CreateUserStatus.EmailNotNull);
                    return View(model);
                }
                model.Email = model.Email.Trim();
                if (!model.Email.IsEmail())
                {
                    ShowLocalError(CreateUserStatus.EmailInvalid);
                    return View(model);
                }
                model.RegisterIP = Request.UserHostAddress;
                var status = model.Save();
                if (status == CreateUserStatus.Created || status == CreateUserStatus.Updated)
                    ShowLocalSuccess(status);
                else
                    ShowLocalError(status);
            }
            return View(model);
        }

        /// <summary>
        /// 验证用户名。
        /// </summary>
        /// <param name="userName">用户名称。</param>
        /// <param name="userID">用户ID。</param>
        /// <returns>返回验证结果。</returns>
        public ActionResult CheckUserName(string userName, int userID)
        {
            if (Components.DisallowNames.Current.IsDeny(userName))
                return Json(Local(CreateUserStatus.UserNameIsDeny), JsonRequestBehavior.AllowGet);
            if (Users.IsNameAvailable(userID, userName))
                return Json(true, JsonRequestBehavior.AllowGet);
            return Json(Local(CreateUserStatus.DuplicateUserName), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 验证显示名称。
        /// </summary>
        /// <param name="displayName">显示名称。</param>
        /// <param name="userID">用户ID。</param>
        /// <returns>返回验证结果。</returns>
        public ActionResult CheckDisplayName(string displayName, int userID)
        {
            if (Components.DisallowNames.Current.IsDeny(displayName))
                return Json(Local(CreateUserStatus.DisplayNameIsDeny), JsonRequestBehavior.AllowGet);
            if (Users.IsDisplayNameAvailable(userID, displayName))
                return Json(true, JsonRequestBehavior.AllowGet);
            return Json(Local(CreateUserStatus.DuplicateDisplayName), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 用户列表。
        /// </summary>
        /// <returns></returns>
        public ActionResult UserList()
        {
            ViewBag.PageSize = BSettings.UserSize;
            return View();
        }

        /// <summary>
        /// 检索用户。
        /// </summary>
        /// <returns>返回JSON实例。</returns>
        [HttpPost]
        public ActionResult QueryUsers(FormCollection form)
        {
            int size;
            var query = new UserQuery
            {
                PageSize = PageSize,
                PageIndex = PageIndex,
                OrderBy = OrderBy("UserID DESC"),
                RoleLevel = form.Get<RoleLevel?>("role", null)
            };
            var users = query.Load(out size);
            return Json(new
            {
                data = users.ConvertAll(user => new
                {
                    UserID = user.UserID,
                    UserName = user.UserName,
                    RoleLevel = Local(user.RoleLevel),
                    AccountStatus = Local(user.AccountStatus),
                    CreateDate = user.CreateDate.ToString(),
                    DisplayName = user.DisplayName,
                    Email = user.Email
                }),
                size = size
            });
        }

        /// <summary>
        /// 删除用户。
        /// </summary>
        /// <param name="ids">用户ID集合。</param>
        /// <returns>返回删除结果。</returns>
        [HttpDelete]
        public ActionResult DeleteUsers(string ids)
        {
            if (ids == null)
                return Json(new { error = Local("CreateUserStatus_DeletedError") });
            if ((ids + ",").IndexOf(Self.UserID + ",") != -1)
                return Json(new { error = Local("CreateUserStatus_DeletedSelfError") });
            if (!Users.DeleteUsers(ids))
                return Json(new { error = Local("CreateUserStatus_DeletedError") });
            return Json(new { message = Local("CreateUserStatus_Deleted") });
        }

        /// <summary>
        /// 肮脏词语过滤器。
        /// </summary>
        /// <returns>肮脏词语过滤器。</returns>
        public ActionResult BadWords()
        {
            string words = null;
            var path = Cores.MapPath("~/App_Data/BadWord.moz");
            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                var reader = new StreamReader(fs, Encoding.UTF8);
                words = reader.ReadToEnd();
                reader.Close();
                fs.Close();
            }
            ViewBag.Words = words;
            return View();
        }

        /// <summary>
        /// 肮脏词语过滤器。
        /// </summary>
        /// <param name="words">肮脏词汇。</param>
        /// <returns>肮脏词语过滤器。</returns>
        [HttpPost]
        public ActionResult BadWords(string words)
        {
            var path = Cores.MapPath("~/App_Data/BadWord.moz");
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                var writer = new StreamWriter(fs, Encoding.UTF8);
                writer.Write(words);
                writer.Close();
                fs.Close();
            }
            ShowLocalSuccess("WordFilters_SaveSuccess");
            return View();
        }

        /// <summary>
        /// 网站设置。
        /// </summary>
        /// <param name="cultureName">资源区域语言。</param>
        /// <returns>返回试图结果。</returns>
        public ActionResult SSettings(string cultureName = null) {
            var settings = SiteSettings.GetConfiguration(cultureName ?? CultureName);
            return View(settings);
        }

        /// <summary>
        /// 网站设置。
        /// </summary>
        /// <returns>全局设置。</returns>
        [HttpPost]
        public ActionResult SSettings(SiteSettings settings)
        {
            if (TryValidateModel(settings))
            {
                if (settings.Save())
                    ShowLocalSuccess("SiteSettings_SaveSuccess");
                else
                    ShowLocalError("SiteSettings_SaveError");
            }
            return View(settings);
        }
    }
}
